package com.maozzi.service.user.business;

import com.maozzi.api.user.UserService;
import com.maozzi.api.user.model.TokenDTO;
import com.maozzi.api.user.model.UserDTO;
import com.maozzi.common.constant.ErrorCodeConstant;
import com.maozzi.common.exception.BizException;
import com.maozzi.common.util.CloneUtil;
import com.maozzi.common.util.TokenUtil;
import com.maozzi.service.user.domain.UserDomainService;
import com.maozzi.service.user.repository.model.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 用户
 *
 * @author maozi
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDomainService userDomainService;

    @Override
    public UserDTO getUser(Long userId) throws BizException {
        User user = userDomainService.getUser(userId);
        if (ObjectUtils.isEmpty(user)) {
            throw new BizException(ErrorCodeConstant.NOT_FOUND, "用户不存在");
        }
        return CloneUtil.to(user, UserDTO.class);
    }

    @Override
    public TokenDTO login(String name, String password) throws BizException {
        UserDTO userDTO = getUser(name, password);
        TokenDTO tokenDTO = CloneUtil.to(userDTO, TokenDTO.class);
        Objects.requireNonNull(tokenDTO).setToken(TokenUtil.getToken(tokenDTO.getId()));
        return tokenDTO;
    }

    /**
     * 通过名称和密码查询用户
     *
     * @param name     名称
     * @param password 密码
     * @return 返回
     */
    private UserDTO getUser(String name, String password) {
        User user = userDomainService.getUser(name, password);
        if (ObjectUtils.isEmpty(user)) {
            throw new BizException(ErrorCodeConstant.FAILED_OPERATION, "用户名或密码错误");
        }
        return CloneUtil.to(user, UserDTO.class);
    }
}
